/**
 * @计算一个数的平方根
 *
 * @author	 wangshikun <wangshikun2010@gmail.com>
 * @copyright	(c) 2012 wangshikun <wangshikun2010@gmail.com>
 * @license	http://www.opensource.org/licenses/mit-license.php The MIT License
 * @package	default
 * @subpackage	default
 */

#include <stdio.h>
#include <cs50.h>

float absoluteValue(float x);
float squareRoot(float x);

int main(int argc, char *argv[]) {

	printf("please enter a number:");
	float x = GetFloat();

	printf("squareRoot(%f) = %f\n", x, squareRoot(x));

	return 0;
}

float absoluteValue(float x) {
	if (x < 0) {
		x = -x;
	} 

	return x;
}

float squareRoot(float x) {
	const float epsilon = 0.00001;
	float guess = 1.0;

	if (x < 0) {
		printf("sorry, number entered is out of range!\n");
		return -1;
	} else if (x == 0){
		return x;
	}

	while (absoluteValue(guess * guess - x) >= epsilon) {
		guess = (x / guess + guess) / 2;
	}

	return guess;
}

